package com.zeker.common.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 转换为HTTP请求/响应
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 1. 排除不需要拦截的路径（如登录接口）
        String requestURI = httpRequest.getRequestURI();
        if (requestURI.contains("/login") || requestURI.contains("/register")) {
            chain.doFilter(request, response); // 直接放行
            return;
        }

        // 2. 从请求头获取Token
        String token = httpRequest.getHeader("Authorization");

        // 3. 验证Token（实际项目中需结合Redis/数据库校验）
        if (token == null || token.trim().isEmpty()) {
            httpResponse.setContentType("application/json;charset=UTF-8");
            httpResponse.getWriter().write("{\"code\":401,\"msg\":\"未登录，请先登录\"}");
            return;
        }

        // 4. Token有效，放行继续处理请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
